<template>
  <div class="container">
    <!-- 树状结构 -->
    <div class="left-panel">
      <el-tree
        :data="treeData"
        :props="treeProps"
        default-expand-all
        @node-click="handleNodeClick"
        ref="warehouseTree"
      >
        <template #default="scope">
          <div class="tree-node-container">
            <!-- 显示节点名称 -->
            <span class="node-name">{{ scope.node.label }}</span>
            <!-- 增加按钮 -->
            <el-button type="text" size="small" class="add-btn">
              增加
            </el-button>

            <!-- 删除按钮（仅在有节点ID时显示，避免无数据时异常） -->
            <el-button
              v-if="scope.node.data.id"
              type="text"
              size="small"
              class="delete-btn"
              @click.stop="handleNodeDelete(scope.node.data.id)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-tree>
    </div>

    <!-- 表单模块 -->
    <div class="right-panel">
      <el-form :model="form" label-width="120px" class="warehouse-form">
        <!-- 上级仓库名称 -->
        <el-form-item label="上级仓库名称">
          <el-input v-model="form.parentWarehouseName" disabled style="width: 320px" />
        </el-form-item>

        <!-- 当前仓库名称 -->
        <el-form-item label="当前仓库名称*">
          <el-input
            v-model="form.currentWarehouseName"
            placeholder="请输入当前仓库名称"
            style="width: 320px"
          />
        </el-form-item>

        <!-- 仓库代码 -->
        <el-form-item label="仓库代码*">
    <el-input
      v-model="form.warehouseCode"
      placeholder="自动生成（CK开头+4位随机数）"
      style="width: 320px"
      disabled  
      readonly  
    />
    <!-- 可选：添加“重新生成”按钮，允许用户刷新代码 -->
    <el-button 
      type="text" 
      size="small" 
      @click="generateWarehouseCode"
      style="margin-left: 8px"
    >
      重新生成
    </el-button>
  </el-form-item>

        <!-- 排列序列 -->
        <el-form-item label="排列序列">
          <el-input
            v-model.number="form.sortOrder"
            placeholder="请输入排列序列"
            type="number"
            style="width: 320px"
          />
        </el-form-item>

        <!-- 仓库地址 - 省市区下拉（整合后的区域选择） -->
        <el-form-item label="仓库地址">
          <el-select
            v-model="selectedProvinceCode"
            placeholder="省"
            style="width: 100px; margin-right: 8px"
          >
            <el-option
              v-for="p in provinceList"
              :key="p.code"
              :label="p.name"
              :value="p.code"
            />
          </el-select>

          <el-select
            v-model="selectedCityCode"
            placeholder="市"
            style="width: 100px; margin-right: 8px"
            :disabled="!cityList.length"
          >
            <el-option
              v-for="c in cityList"
              :key="c.code"
              :label="c.name"
              :value="c.code"
            />
          </el-select>

          <el-select
            v-model="selectedArea"
            placeholder="区"
            style="width: 100px"
            :disabled="!areaList.length"
          >
            <el-option
              v-for="(a, i) in areaList"
              :key="i"
              :label="a"
              :value="a"
            />
          </el-select>
        </el-form-item>

        <!-- 详细地址 -->
        <el-form-item label="详细地址">
          <el-input
            v-model="form.detailAddress"
            placeholder="请输入详细地址"
            style="width: 320px"
          />
        </el-form-item>

        <!-- 实体仓库 -->
        <el-form-item label="实体仓库">
          <el-radio-group v-model="form.isPhysical">
            <el-radio label="1">实体仓</el-radio>
            <el-radio label="0">虚拟仓</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 当前状态 -->
        <el-form-item label="当前状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import { addStore, tree, deleCk } from "@/api/set/product.js";
import areaObj from "@/data/area.json";

// 表单数据
const form = reactive({
  parentWarehouseId: "", // 新增：存储上级仓库ID（传给接口的fuId）
  parentWarehouseName: "", // 上级仓库名称
  currentWarehouseName: "", // 当前仓库名称
  warehouseCode: "", // 仓库代码
  sortOrder: "", // 排列序列
  detailAddress: "", // 详细地址
  isPhysical: "1", // 实体仓库，1为实体仓，0为虚拟仓
  status: "1" // 当前状态，1为启用，0为停用
});


// 2. 仓库代码自动生成函数（CK开头 + 4位随机数）
const generateWarehouseCode = () => {
  // 生成4位随机数（不足4位补0，确保格式统一）
  const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
  // 拼接前缀CK，赋值给表单
  form.warehouseCode = `CK${randomNum}`;
};

// 省市区选择相关数据
const provinceList = computed(() =>
  Object.entries(areaObj["00"]).map(([code, name]) => ({ code, name }))
);
const selectedProvinceCode = ref();

const cityList = computed(() =>
  selectedProvinceCode.value
    ? Object.entries(areaObj[selectedProvinceCode.value] || {}).map(
        ([code, name]) => ({ code, name })
      )
    : []
);
const selectedCityCode = ref(cityList.value[0]?.code || "");

const areaList = computed(() =>
  selectedProvinceCode.value && selectedCityCode.value
    ? areaObj[selectedProvinceCode.value][selectedCityCode.value] || []
    : []
);
const selectedArea = ref(areaList.value[0] || "");

// 监听省份变化重置城市
watch(selectedProvinceCode, () => {
  selectedCityCode.value = cityList.value[0]?.code || "";
  // 将选中值同步到表单
  form.province = selectedProvinceCode.value;
});

// 监听城市变化重置区域
watch(selectedCityCode, () => {
  selectedArea.value = areaList.value[0] || "";
  // 将选中值同步到表单
  form.city = selectedCityCode.value;
});

// 监听区域变化
watch(selectedArea, () => {
  // 将选中值同步到表单
  form.district = selectedArea.value;
});

// 节点点击事件 同时保存ID和名称
const handleNodeClick = data => {
   form.parentWarehouseId = data.id;
  form.parentWarehouseName = data.name;
};

// 保存按钮事件
const handleSave = () => {
  console.log("保存!!!!");
  ADDStore();
};

// 增加仓库
async function ADDStore() {
  // 准备提交的数据，包含省市区信息
  const submitData = {
    fuId: form.parentWarehouseId,
    name: form.currentWarehouseName,
    code: form.warehouseCode,
    sorts: form.sortOrder,
    province: selectedProvinceCode.value, // 使用区域选择的省份编码
    city: selectedCityCode.value, // 使用区域选择的城市编码
    area: selectedArea.value, // 使用区域选择的区域
    address: form.detailAddress,
    isentity: form.isPhysical,
    status: form.status
  };

  const res = await addStore(submitData);
  console.log(res);

  if (res.code === 200) {
    ElMessage({
      message: "添加成功",
      type: "success"
    });
     getTreeData();
  } else {
    ElMessage.error("添加失败");
  }
}
//删除仓库
async function handleNodeDelete(id) {
  
  const res = await deleCk(id);
  console.log(res);
  if (res.code === 200) {
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    //  window.location.reload(); 
    getTreeData();
  } else {
    ElMessage.error("删除失败");
  }
}


// 取消按钮事件 内容清空
const handleCancel = () => {
  console.log("取消!!!!");
  // 重置表单数据为初始状态
  Object.assign(form, {
    parentWarehouseName: "",
    currentWarehouseName: "",
    warehouseCode: "",
    sortOrder: "",
    detailAddress: "",
    isPhysical: "1",
    status: "1",
  
  });

  // 重置区域选择
  selectedProvinceCode.value = ""; // 清空省份选择
  selectedCityCode.value = "";     // 清空城市选择
  selectedArea.value = "";         // 清空区域选择

  generateWarehouseCode();
};

// 页面挂载
onMounted(async () => {
  getTreeData();
  generateWarehouseCode();
});

// 配置Tree组件字段映射
const treeProps = reactive({
  label: "name", // 节点显示的文本对应接口的`name`字段
  children: "storeslist" // 子节点数组对应接口的`storeslist`字段
});

// Tree组件的数据源
const treeData = ref([]);

// 获取树形结构数据
async function getTreeData() {
  try {
    const res = await tree();
    if (res.code === 200) {
      treeData.value = res.data;
    } else {
      ElMessage.warning("树状数据获取失败");
    }
  } catch (error) {
    ElMessage.error("加载失败：" + error.message);
  }
}

</script>

<style scoped>
.container {
  display: flex;
  gap: 20px;
  padding: 20px;
}

.left-panel {
  flex: 0 0 300px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 10px;
}

.right-panel {
  flex: 1;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 20px;
}

.warehouse-form {
  max-width: 600px;
}

.tree-node-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.delete-btn {
  color: #f56c6c;
  margin-left: 10px;
}
.add-btn {
  color: #22c6e3;
  margin-left: 10px;
  margin-left: auto;
}
/* 解决按钮 hover 时背景溢出问题 */
.delete-btn:hover {
  background-color: transparent;
}
</style>
